package com.cskaoyan.util;

import org.apache.ibatis.session.SqlSession;

/**
 * @author stone
 * @date 2023/03/18 01:51
 */
public class TransactionUtil {
    private static ThreadLocal<SqlSession> localVar = new ThreadLocal<SqlSession>();

    public static void startTransaction() {
        setSqlSession();
    }

    public static void commit() {
        SqlSession sqlSession = localVar.get();
        System.out.println("sqlSession = " + sqlSession);
        if (sqlSession != null) {
            sqlSession.commit();
            sqlSession.close();
        }
    }
    public static void rollback() {
        SqlSession sqlSession = localVar.get();
        System.out.println("sqlSession = " + sqlSession);
        if (sqlSession != null) {
            sqlSession.rollback();
            sqlSession.close();
        }
    }

    private static void setSqlSession() {
        SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
        System.out.println("存入sqlSession = " + sqlSession);
        localVar.set(sqlSession);
    }

    public static SqlSession getSqlSession() {
        SqlSession sqlSession = localVar.get();
        if (sqlSession == null) {
            setSqlSession();
            return localVar.get();
        }
        return sqlSession;
    }

    public static <T> T getMapper(Class<T> mapperClass) {
        T mapper = getSqlSession().getMapper(mapperClass);
        return mapper;
    }
}
